package com.hyh.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class EncodingFileter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        request.setCharacterEncoding("utf-8");
        String uri = request.getRequestURI();
        System.out.println("请求地址为："+uri);
        Object userName = request.getSession().getAttribute("userName");
        Object password = request.getSession().getAttribute("password");
        if (uri.endsWith("/show.jsp") || uri.endsWith("/head.jsp") || uri.endsWith("/left.jsp") || uri.endsWith("/right.jsp")) {
            if(userName == null && password ==null ) {
                response.setContentType("text/html;charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.println("<script>alert('请先登录用户！');</script>");
                request.getRequestDispatcher("/login.jsp").forward(request, response);
                System.out.println("跳转");
            }
        }
        filterChain.doFilter(servletRequest,servletResponse);

    }

    @Override
    public void destroy() {

    }
}









